package com.apach.shiro.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyRealm1 extends AuthorizingRealm {

  private Logger _log = LoggerFactory.getLogger(MyRealm1.class);
  
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    String username = (String)principals.getPrimaryPrincipal(); 
    _log.debug("AuthorizationInfo and username is {}", username);
    
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //权限
    Set<String> s = new HashSet<String>();
    s.add("printer:*");
    s.add("printer:query");
    info.setStringPermissions(s);
    //角色
    Set<String> r = new HashSet<String>();
    r.add("role1");
    info.setRoles(r);

    return info;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {
    String username = (String)token.getPrincipal();  //得到用户名  
    String password = new String((char[])token.getCredentials()); //得到密码 
    if(!"zhang".equals(username)) {
        _log.error("username is not correct");
        throw new UnknownAccountException(); //如果用户名错误  
    }  
    if(!"123".equals(password)) {
        _log.error("password is not correct");
        throw new IncorrectCredentialsException(); //如果密码错误  
    }  
    //如果身份认证验证成功，返回一个AuthenticationInfo实现；  
    return new SimpleAuthenticationInfo(username, password, "MyRealm1");
  }

  
}
